import os
import json
import time
import logging
from datetime import datetime
from config import OUTPUT_DIR

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def save_result(result, prefix="result", output_dir=None):
    """
    保存结果到文件

    参数:
        result: 要保存的结果
        prefix: 文件名前缀
        output_dir: 输出目录，默认为配置中的目录

    返回:
        保存的文件路径
    """
    output_dir = output_dir or OUTPUT_DIR
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"{prefix}_{timestamp}.json"
    filepath = os.path.join(output_dir, filename)

    try:
        # 只保存文本信息，不包含图像二进制数据
        text_result = {
            "parameters": result.get("parameters", {}),
            "prompt": result.get("prompt", ""),
            "output": result.get("output", ""),
            "image_path": result.get("image_path", "")
        }

        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(text_result, f, ensure_ascii=False, indent=2)
        logger.info(f"结果已保存至 {filepath}")
        return filepath
    except Exception as e:
        logger.error(f"保存结果失败: {str(e)}")
        return None


def load_example(example_name):
    """
    加载示例数据

    参数:
        example_name: 示例名称（不含扩展名）

    返回:
        示例数据
    """
    from config import EXAMPLES_DIR
    filepath = os.path.join(EXAMPLES_DIR, f"{example_name}.json")

    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        logger.error(f"加载示例 {example_name} 失败: {str(e)}")
        return None


def create_example(example_name, data):
    """创建示例数据文件"""
    from config import EXAMPLES_DIR
    filepath = os.path.join(EXAMPLES_DIR, f"{example_name}.json")

    try:
        with open(filepath, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        logger.info(f"示例已创建至 {filepath}")
        return filepath
    except Exception as e:
        logger.error(f"创建示例 {example_name} 失败: {str(e)}")
        return None


def timer_decorator(func):
    """计时器装饰器，用于测量函数执行时间"""

    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        logger.info(f"{func.__name__} 执行时间: {end_time - start_time:.4f} 秒")
        return result

    return wrapper


def compare_results(results):
    """
    比较多个结果

    参数:
        results: 结果列表，每个结果应包含"parameters"和"output"键

    返回:
        比较分析结果
    """
    if not results or len(results) < 2:
        logger.warning("需要至少两个结果进行比较")
        return None

    analysis = {
        "total_results": len(results),
        "comparison_notes": [],
        "length_statistics": []
    }

    # 分析提示词长度差异
    for result in results:
        length = len(result.get("prompt", ""))
        analysis["length_statistics"].append({
            "parameters": result.get("parameters", {}),
            "prompt_length": length,
            "image_path": result.get("image_path", "")
        })

    # 按提示词长度排序
    analysis["length_statistics"].sort(key=lambda x: x["prompt_length"], reverse=True)

    # 简单的差异分析
    if len(results) >= 2:
        longest = analysis["length_statistics"][0]
        shortest = analysis["length_statistics"][-1]
        analysis["comparison_notes"].append(
            f"最长提示词 ({longest['prompt_length']} 字符) 使用参数: {longest['parameters']}"
        )
        analysis["comparison_notes"].append(
            f"最短提示词 ({shortest['prompt_length']} 字符) 使用参数: {shortest['parameters']}"
        )

    return analysis